package test.check.system.remote;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerWorker implements Runnable {
	Socket client = null;
	InputStream clientInputStream = null;
	OutputStream clientOutputStream = null;
	
	public ServerWorker() {
		
	}
	
	public ServerWorker(Socket client) throws IOException {
		this.client = client;
		this.clientInputStream = client.getInputStream();
		this.clientOutputStream = client.getOutputStream();
	}
	
	@Override
	public void run() {
		BufferedReader br = new BufferedReader(new InputStreamReader(clientInputStream));
		PrintWriter pw = new PrintWriter(clientOutputStream);
		BufferedReader stdInput = new BufferedReader(new InputStreamReader(System.in));
		
		String line = null;
		String resultLine = null;
		try {
			while((line = br.readLine()) != null) {
				if(line.contains("Check")) {
					System.out.println(line);
					break;
				}
			}
			
			String prompt = "Enter shell command : ";
			System.out.print(prompt);
			while((line = stdInput.readLine()) != null) {
				pw.println(line);
				pw.flush();
				
				while((resultLine = br.readLine()) != null) {
					if("@result end".equals(resultLine)) {
						break;
					} else {
						System.out.println(resultLine);
					}
				}
				System.out.print(prompt);
			}
			


			br.close();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		System.out.println("Server-Client connection has established successfully");
		
	}
}
